package com.lwt.gulimall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lwt.gulimall.product.entity.Category;
import com.lwt.gulimall.product.entity.CategoryBrandRelation;
import com.lwt.gulimall.product.mapper.CategoryMapper;
import com.lwt.gulimall.product.service.CategoryBrandRelationService;
import com.lwt.gulimall.product.service.CategoryService;
import com.lwt.gulimall.product.vo.CategoryVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
*
*/
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category>
implements CategoryService{
    @Autowired
    private CategoryMapper categoryMapper;

    @Autowired
    private CategoryBrandRelationService categoryBrandRelationService;

    @Override
    public void removeMenuByIds(Long[] catIds) {
        categoryMapper.updateMenuByIds(catIds);
    }

    @Override
    public List<CategoryVo> listTree() {
        List<CategoryVo> list = this.list().stream().map(category -> {
            CategoryVo categoryVo = new CategoryVo();
            BeanUtils.copyProperties(category, categoryVo);
            return categoryVo;
        }).sorted(Comparator.comparingInt(category -> Optional.ofNullable(category.getSort()).orElse(0)))
                .collect(Collectors.toList());

/*        // 获取所有分类按 级别 分组
        Map<Integer, List<CategoryVo>> categoryCatLevelMap = list.stream().collect(Collectors.groupingBy(CategoryVo::getCatLevel));
        Map<Long, List<CategoryVo>> categoryParentCidMap = list.stream().collect(Collectors.groupingBy(CategoryVo::getParentCid));
        // 整合二级分类
        Map<Long, List<CategoryVo>> secondCategoryMap = categoryCatLevelMap.get(2).stream().peek(categoryVo -> {
            categoryVo.setChildrenList(categoryParentCidMap.get(categoryVo.getCatId()));
        }).collect(Collectors.groupingBy(CategoryVo::getParentCid));
        // 整合一级分类
        List<CategoryVo> collect = categoryCatLevelMap.get(1).stream().peek(categoryVo -> {
            categoryVo.setChildrenList(secondCategoryMap.get(categoryVo.getCatId()));
        }).collect(Collectors.toList());*/
        return initTree(list);
    }

    private List<CategoryVo> initTree(List<CategoryVo> categoryVoList) {
        Map<Integer, List<CategoryVo>> categoryCatLevelMap = categoryVoList.stream().collect(Collectors.groupingBy(CategoryVo::getCatLevel));
        Map<Long, List<CategoryVo>> categoryParentCidMap = categoryVoList.stream().collect(Collectors.groupingBy(CategoryVo::getParentCid));
        int size = categoryCatLevelMap.size();
        //处理倒数第二级的分类子类
        Map<Long, List<CategoryVo>> oldCategoryMap = categoryCatLevelMap.get(size - 1).stream()
                .peek(categoryVo -> {
                    categoryVo.setChildrenList(categoryParentCidMap.get(categoryVo.getCatId()));
                })
                .collect(Collectors.groupingBy(CategoryVo::getParentCid));
        //处理倒数第三级到正数第第二级的分类子类
        for (int i = size - 2; i >= 2; i--) {
            Map<Long, List<CategoryVo>> oldMap = categoryCatLevelMap.get(i)
                    .stream().peek(categoryVo -> {
                        categoryVo.setChildrenList(oldCategoryMap.get(categoryVo.getCatId()));
                    })
                    .collect(Collectors.groupingBy(CategoryVo::getParentCid));
            oldCategoryMap.clear();
            oldCategoryMap.putAll(oldMap);
        }
        //处理第一级的分类子类
        return categoryCatLevelMap.get(1)
                .stream().peek(categoryVo -> {
                    categoryVo.setChildrenList(oldCategoryMap.get(categoryVo.getCatId()));
                })
                .collect(Collectors.toList());
    }

    @Override
    public Long[] getCategoryPath(Long categoryId) {
        List<Long> path = new ArrayList<>();
        findParentId(categoryId, path);
        Collections.reverse(path);
        System.out.println(path);
/*        Category byId = this.getById(categoryId);
        Category byId1 = this.getById(byId.getParentCid());
         return new Long[]{byId1.getParentCid(),byId1.getCatId(),categoryId};*/
        return path.toArray(new Long[0]);
    }

    /*递归找父类id，返回集合*/
    private void findParentId(Long categoryId,List<Long> path){
        if(!categoryId.equals(0L)){
            path.add(categoryId);
            Category category = this.getById(categoryId);
            findParentId(category.getParentCid(),path);
        }
    }

    @Override
    public void updateDetail(Category category) {
        this.updateById(category);
        categoryBrandRelationService.update(new LambdaUpdateWrapper<CategoryBrandRelation>().eq(CategoryBrandRelation::getCatelogId,category.getCatId()).set(CategoryBrandRelation::getCatelogName,category.getName()));
    }
}
